﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;

namespace Web.Controllers
{
    /// <summary>
    /// 防空过滤器
    /// </summary>
    public class ParamsNoEmpty : ActionFilterAttribute
    {
        public string[] Params;
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            List<string> needs = new List<string>();
            if (Params == null)
            {
                foreach (var p in context.ActionParameters)
                    if (p.Value == null || p.Value.ToString() == "")
                        needs.Add(p.Key);
            }
            else
                foreach (var param in Params)
                    if ((context.ActionParameters[param] ?? "").ToString() == "")
                        needs.Add(param);
            if (needs.Count > 0)
            {
                StringBuilder str = new StringBuilder("以下参数必须非空：");
                for (int i = 0; i < needs.Count - 1; ++i)
                    str.AppendFormat("{0}, ", needs[i]);
                str.AppendFormat("{0}。请检查后重试。", needs.Last());
                context.Result = new JsonString(new
                {
                    success = false,
                    msg = str.ToString()
                });
            }
        }
    }
}
